package site.zhangzhuo.learn_springboot.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Before("execution(* site.zhangzhuo.learn_springboot.aop.MyService.performAction(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("@Before: Before calling performAction");
    }

    @After("execution(* site.zhangzhuo.learn_springboot.aop.MyService.performAction(..))")
    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("@After: After calling performAction");
    }

    @AfterReturning(pointcut = "execution(* site.zhangzhuo.learn_springboot.aop.MyService.performAction(..))", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("@AfterReturning: Method returned value is : " + result);
    }

    @AfterThrowing(pointcut = "execution(* site.zhangzhuo.learn_springboot.aop.MyService.performAction(..))", throwing = "ex")
    public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("@AfterThrowing: Exception in method: " + methodName + "; Exception: " + ex.toString());
    }

    @Around("execution(* site.zhangzhuo.learn_springboot.aop.MyService.performAction(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("@Around: Before method execution");
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            // 如果执行方法出现异常，打印这里
            System.out.println("@Around: Exception in method execution");
            throw throwable;
        }
        // 如果执行方法正常，打印这里
        System.out.println("@Around: After method execution");
        return result;
    }
}
